package com.xc.pay.ali.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.xc.pay.ali.constant.AliProperties;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Filename: AliAppPayAsyncNotifyVerify.java <br>
 * Description: 支付宝app支付回调异步通知验证<br>
 *
 * @author: rongrong <br>
 * @version: 1.0 <br>
 */
@Slf4j
public class AliAppPayAsyncNotifyVerify {

  /**
   * 回调验签
   *
   * @param request 回调参数信息
   * @param isChangeCharSet 是否乱码需要解决
   * @param aliPublicKey 支付宝公钥
   * @return 是否正常
   */
  public static boolean alipayNotify(
      HttpServletRequest request, boolean isChangeCharSet, String aliPublicKey)
      throws AlipayApiException {
    // 获取支付宝POST过来反馈信息
    log.info("支付宝回调验签...");
    Map<String, String> params = new HashMap<>();
    Map<String, String[]> requestParams = request.getParameterMap();
    for (String name : requestParams.keySet()) {
      String[] values = requestParams.get(name);
      String valueStr = "";
      for (int i = 0; i < values.length; i++) {
        valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
      }
      // 乱码解决，这段代码在出现乱码时使用。
      if (isChangeCharSet) {
        try {
          valueStr =
              new String(
                  valueStr.getBytes(StandardCharsets.ISO_8859_1.name()),
                  StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
          throw new AlipayApiException(e.getMessage());
        }
      }
      params.put(name, valueStr);
    }
    // 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看
    // 验签不通过无返回信息支付宝会一直回调 异步回调。
    try {
      return AlipaySignature.rsaCheckV1(
          params,
          // 这里是支付宝公钥不是应用公钥
          aliPublicKey,
          AliProperties.CHARSET,
          AliProperties.SIGNTYPE);
    } catch (AlipayApiException e) {
      throw new AlipayApiException(e.getMessage());
    }
  }
}
